package com.link.base.base.activity.controller;

import com.link.base.user.model.CoreUser;
import com.link.base.base.activity.model.FlowUp;
import com.link.base.base.activity.service.FlowUpService;
import com.link.core.cllog.LCLogger;
import com.link.core.basic.annotations.JsonParam;
import com.link.core.basic.controller.BasicController;
import com.link.core.basic.model.BasicModel;
import com.link.core.basic.query.QueryParams;
import com.link.core.basic.query.Sorter;
import com.link.core.basic.service.BasicService;
import com.link.core.basic.service.BasicServiceException;
import com.link.core.basic.service.KeyGenerateService;
import com.link.core.basic.service.ServiceException;
import com.link.core.util.StringUtils;
import com.link.core.util.UserUtil;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Copyright  hande Company. All Rights Reserved.
 *
 * @author unknwon
 * @version 1.0
 * @date: 2018/11/8 9:39
 */

@Controller
@RequestMapping("/link/flowUp")
public class FlowUpController extends BasicController<FlowUp> {

    @Resource
    private FlowUpService flowUpService;
    @Resource
    private KeyGenerateService keyGenerateService;

    @Override
    public BasicService<FlowUp> getBasicService() throws Exception {
        return flowUpService;
    }

    /**
     * 分页查询跟进列表
     *
     * @param qps
     * @param entity
     * @param session
     * @param request
     * @param response
     * @return
     */
    @Override
    @RequestMapping(value = "/queryByExamplePage", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> queryByExamplePage(@JsonParam QueryParams qps, @JsonParam FlowUp entity, HttpSession session,
                                                  HttpServletRequest request, HttpServletResponse response) {
        LCLogger.info().withMessageKey("queryByExamplePage").withMessage("查询跟进列表.").flush();
        Map<String, Object> result = new HashMap<String, Object>(4);
        try {
            qps.addSorter(new Sorter("dt", Sorter.DIR_DESC));
            qps.preDealSecurity(request);
            FlowUp t = (FlowUp) BasicModel.transformClass(FlowUp.class, qps);
            t.setOptyId(entity.getOptyId());
            t.setAccntId(entity.getAccntId());
            t.setClueId(entity.getClueId());
            t.setOrderId(entity.getOrderId());
            t.setServiceId(entity.getServiceId());
            String type = entity.getType();
            if (type == null || "".equals(type)) {
                //默认为"跟进类型"
                type = "TUDO_CD_FLOW_UP";
            }
            t.setType(type);
            List<FlowUp> list = getBasicService().queryByExamplePage(t);
            result.put("success", true);
            result.put("rows", list);
            this.pushCurrentDataCache(list, session.getId(), "base", false);
            result.put("total", getCount(t, list.size()));
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("rows", new ArrayList<FlowUp>());
            result.put("result", e.getMessage());
        }
        return result;
    }

    /**
     * 查询所有
     *
     * @param qps
     * @param entity
     * @param session
     * @param request
     * @param response
     * @return
     */
    @Override
    @RequestMapping(value = "/queryAll", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> queryAll(@JsonParam QueryParams qps, @JsonParam FlowUp entity, HttpSession session,
                                        HttpServletRequest request, HttpServletResponse response) {
        LCLogger.info().withMessageKey("queryAll").withMessage("查询所有跟进列表.").flush();
        Map<String, Object> result = new HashMap<String, Object>(4);
        try {
            qps.addSorter(new Sorter("dt", Sorter.DIR_ASC));
            qps.preDealSecurity(request);
            String isSystem = entity.getIsSystem();
            FlowUp t = (FlowUp) BasicModel.transformClass(FlowUp.class, qps);
            t.setIsSystem(isSystem);
            t.setOptyId(entity.getOptyId());
            t.setAccntId(entity.getAccntId());
            t.setClueId(entity.getClueId());
            t.setOrderId(entity.getOrderId());
            t.setServiceId(entity.getServiceId());
            //默认为"跟进类型"
            if (entity.getType() == null || "".equals(entity.getType())) {
                String type = "TUDO_CD_FLOW_UP";
                t.setType(type);
            } else {
                t.setType(entity.getType());
            }
            List<FlowUp> list = getBasicService().queryAll(t);
            result.put("success", true);
            result.put("rows", list);
            this.pushCurrentDataCache(list, session.getId(), "base", false);
            result.put("total", getCount(t, list.size()));
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("rows", new ArrayList<FlowUp>());
            result.put("result", e.getMessage());
        }
        return result;
    }

    /**
     * 新建一条记录
     */
    @RequestMapping(value = "/FlowUpInsert")
    @ResponseBody
    public Map<String, Object> flowUpInsert(@RequestBody FlowUp entity, HttpSession session,
                                            HttpServletRequest request, HttpServletResponse response) {
        LCLogger.info().withMessageKey("FlowUpInsert").withMessage("新建跟进记录." + entity.getId()).flush();
        Map<String, Object> result = new HashMap<String, Object>(4);
        CoreUser user = UserUtil.getUser();
        try {
            SimpleDateFormat dfFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date myDate = new Date();
            String sysdate = dfFormat.format(myDate);
            beforInsert(entity, request);
            beforUpsert(entity, request);
            String type = entity.getType();
            Long id = entity.getId();
            entity.setDt(sysdate);
            if (type == null || "".equals(type)) {
                entity.setType("TUDO_CD_FLOW_UP");
            }
            if (id == null) {
                entity.setId(keyGenerateService.keyGenerate());
            }
            Long empId = entity.getEmpId();
            if (empId == null) {
                entity.setEmpId(user.getId());
            }
            Long orgId = entity.getOrgId();
            if (orgId == null) {
                entity.setOrgId(user.getOrgId());
            }
            Long postnId = entity.getPostnId();
            if (postnId == null) {
                entity.setPostnId(user.getPostnId());
            }
            getBasicService().insert(entity);
            FlowUp newEntry = getBasicService().queryById(entity);
            result.put("newRow", newEntry);
            result.put("success", true);
        } catch (BasicServiceException e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
            result.put("detailMessage", e.getDetailMessage());
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }

    @Override
    public void beforInsert(FlowUp entity, HttpServletRequest request) throws Exception {
        String type = entity.getType();
        if (type == null || "".equals(type)) {
            //默认为"跟进类型"
            entity.setType("TUDO_CD_FLOW_UP");
        }
    }

    @Override
    public void beforDelete(FlowUp entity, HttpServletRequest request) throws Exception {
        Long id = entity.getId();
        if (id == null) {
            throw new ServiceException("PUBLIC-007");
        }
    }


    /**
     * 分页查询跟进列表
     *
     * @param qps
     * @param entity
     * @param session
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/queryProjByExamplePage", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> queryProjByExamplePage(@JsonParam QueryParams qps, @JsonParam FlowUp entity, HttpSession session,
                                                      HttpServletRequest request, HttpServletResponse response) {
        LCLogger.info().withMessageKey("queryProjByExamplePage").withMessage("查询跟进列表.").flush();
        Map<String, Object> result = new HashMap<String, Object>(4);
        try {
            qps.addSorter(new Sorter("dt", Sorter.DIR_DESC));
            qps.preDealSecurity(request);
            FlowUp t = (FlowUp) BasicModel.transformClass(FlowUp.class, qps);
            String optyId = request.getParameter("optyId");
            if (StringUtils.isNotBlank(optyId)) {
                t.setOptyId(Long.parseLong(optyId));
            }
            String accntId = request.getParameter("accntId");
            if (StringUtils.isNotBlank(accntId)) {
                t.setAccntId(Long.parseLong(accntId));
            }
            String clueId = request.getParameter("clueId");
            if (StringUtils.isNotBlank(clueId)) {
                t.setClueId(Long.parseLong(clueId));
            }
            String orderId = request.getParameter("orderId");
            if (StringUtils.isNotBlank(orderId)) {
                t.setOrderId(Long.parseLong(orderId));
            }
            String serviceId = request.getParameter("serviceId");
            if (StringUtils.isNotBlank(serviceId)) {
                t.setServiceId(Long.parseLong(serviceId));
            }
            String type = request.getParameter("type");
            if (type == null || "".equals(type)) {
                //默认为"跟进类型"
                type = "TUDO_CD_FLOW_UP";
            }
            t.setType(type);
            List<FlowUp> list = flowUpService.queryProjByExamplePage(t);
            result.put("success", true);
            result.put("rows", list);
            this.pushCurrentDataCache(list, session.getId(), "base", false);
            result.put("total", getCount(t, list.size()));
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("rows", new ArrayList<FlowUp>());
            result.put("result", e.getMessage());
        }
        return result;
    }

}
